<?php

namespace app\service\common;

use support\Response;

/**
 * 获取车牌信息
 */
class LicensePlate
{

    /**
     * 车牌验证,入口
     * @param $license_plate_code
     * @return array|false|Response
     */
    public function get_license_plate($license_plate_code) {
        if (empty($license_plate_code)) {
            return errorMessage("车牌号码为空");
        }
        $one = mb_substr($license_plate_code, 0, 1);
        if (!preg_match("/[\x7f-\xff]/", $one)) {
            $one = strtoupper(mb_substr($license_plate_code, 0, 2));
            $two = $one;
        } else {
            $str = ltrim($license_plate_code, $one);
            if ($one == '使') {
                $two = mb_substr($str, 0, 3);
            } else {
                $res = $this->carVif($license_plate_code);
                if (!$res) return false;

                $two = strtoupper(mb_substr($str, 0, 1));
            }
        }

        $array = config('license_plate');
        if (!isset($array[$one][$two])) {
            return errorMessage("车牌号码识别失败，联系管理员更新归属地址库");
        }
        $data = $array[$one][$two];
        return [
            'car_prefix' => $one,
            'car_code' => $two,
            'province' => $data['a'],
            'city' => $data['b']
        ];
    }

    /**
     * 车牌号码合法性验证
     * @param $license_plate_code
     * @return Response|true
     */
    private function carVif($license_plate_code){
        $regular = "/[京津冀晋蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云渝藏陕甘青宁新使]{1}[A-Z]{1}[0-9a-zA-Z]{5}$/u";
        preg_match($regular, $license_plate_code, $match);
        if (isset($match[0])) {
            return true;
        }
        #小型新能源车
        $regular = "/[京津冀晋蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云渝藏陕甘青宁新]{1}[A-Z]{1}[DF]{1}[0-9a-zA-Z]{5}$/u";
        preg_match($regular, $license_plate_code, $match);
        if (isset($match[0])) {
            return true;
        }
        #大型新能源车
        $regular = "/[京津冀晋蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云渝藏陕甘青宁新]{1}[A-Z]{1}[0-9a-zA-Z]{5}[DF]{1}$/u";
        preg_match($regular, $license_plate_code, $match);
        if (isset($match[0])) {
            return true;
        }
       return errorMessage("车牌号码格式错误");
    }
}
